var chargingStationData = [];
var chargingStationMap = undefined;
var branchCompanyData = [];
var markers = [];
var selectPosition = [];

$(document).ready(function() {
    showLoading();
    setBaseUrl();
    $ajaxList('branchCompany', getBranchCompany);
    addTitle("chargingStationSave");
    search();
});

function search(){
	$ajax('searchChargingStation', 'searchChargingStationSave', searchChargingStation);
}

function getBranchCompany(data) {
	var length = data.length;
	for (var i = 0;i < length; i++){
    	branchCompanyData = data;
        $("#BranchCompanyID").append("<option value='" + data[i].branchCompanyID + "'>" + data[i].branchCompanyName + "</option>");
    }
}
function searchChargingStation(data) {
	chargingStationData = data && data.chargingstationList || [];
	var index = undefined;
	createComBody("detailOneBody", chargingStationTable, chargingStationData[index], 1);
    createComBody("detailTwoBody", chargingStationTable, chargingStationData[index], 2);
    createComBody("detailThreeBody", chargingStationTable, chargingStationData[index], 3);
	createComBody("detailFourBody", chargingStationTable, chargingStationData[index], 4);
	createComBody("detailFiveBody", chargingStationTable, chargingStationData[index], 5);
	for (var i = 0;i < branchCompanyData.length;i++){
        $("#branchCompanyID").append("<option value='" + branchCompanyData[i].branchCompanyID + "'>" + branchCompanyData[i].branchCompanyName + "</option>");  
	}
	selectDate("openTime", 0, undefined, 1);
	selectDate("closeTime", 0, undefined, 1);
	$("#chargingStationID").attr("readonly", false);
	$('#confirm').show();
	$('#confirmMap').show();
	$("#longitude").attr("readonly", true);
	$("#latitude").attr("readonly", true);
	if (!chargingStationMap) {
		$.getScript("https://webapi.amap.com/maps?v=1.3&key=244bc2cb511336b2a3e5129ad0309a13&&plugin=AMap.OverView,AMap.MapType,AMap.Geolocation,AMap.Scale,AMap.ToolBar,AMap.Autocomplete,AMap.PlaceSearch&callback=tableMap");
	} else {
		tableMap();
	}
	changeImage(index);
	setTimeout(hideLoading, 500);
}
function goback() {
	window.parent.skipMenu('chargingStation/chargingStation', 'drownDown1', '', 'chargingStationPage', 'chargingStation');
}
function tableMap(){
	var longitude = $("#longitude").val();
	var latitude = $("#latitude").val();
	var centerPosition = [];
	if (longitude && latitude && longitude != "-" && latitude != "-") {
		centerPosition.push(longitude);
		centerPosition.push(Number(latitude) + 0.015);
		var position = [];
		position.push(longitude);
		position.push(latitude);
	}
	chargingStationMap = setMap(centerPosition, 'tableContainer', 10);
	addMarker(position, "static/images/chargingStationMapsm.png");
}
function confirmMap(){
	$("#map").modal("hide");
	if (selectPosition && selectPosition.length > 0) {
		$("#longitude").val(selectPosition[0]);
		$("#latitude").val(selectPosition[1]);
	}
	tableMap();
}
function confirm(){
	return checkForm("saveForm", chargingStationTable);
}
function saveChargingStationImage(data){
	var result = data && data.result;
	if (result == "Success") {
		showMessge(messageContent["Insert.Success"], undefined, goback);
	} else {
		var error = data && data.error;
		if (error){
			    showMessge(error);
		} else {
			showMessge(messageContent["Image.Failed"]);
		}
	}
}
function saveChargingStation(data){
     var result = data && data.result;
     var chargingStationID = data && data.chargingStationID;
     if (result == "Success") {
    	 if (chargingStationID) {
    		 if ($('#chargingStationImage').val()) {
    			 $ajaxSubmit("imageForm", 'saveChargingStationImage?subfolder=' + chargingStationID, saveChargingStationImage);
    		 } else {
    			 showMessge(messageContent["Insert.Success"], undefined, goback);
    		 }
    	 } else {
    		 showMessge(messageContent["Image.Failed"]);
    	 }
     } else if (result == "NotFound"){
    	 showMessge(messageContent["Insert.Failed"]);
     } else if (result == "ChargingStationNOExist"){
         showMessge(messageContent["ChargingStation.ChargingStationNOExist"]);
     } else if (result == "ChargingStationNameExist"){
         showMessge(messageContent["ChargingStation.ChargingStationNameExist"]);
     } else {
    	 showMessge(messageContent["Insert.Error"]);
     }
}
function changeGPS() {
	$("#map").modal("show");
	var longitude = $("#longitude").val();
	var latitude = $("#latitude").val();
	var position = [];
	if (longitude && latitude && longitude != "-" && latitude != "-") {
		position.push(longitude);
		position.push(latitude);
	}
	chargingStationMap = setMap(position);
	AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
		var autoOptions = {
			city: '', //城市，默认全国  
	        input: "keyword"//使用联想输入的input的id
	    };
	    autocomplete= new AMap.Autocomplete(autoOptions);
		var placeSearch = new AMap.PlaceSearch({
			city: '', //城市，默认全国  
	        map: chargingStationMap
	    });
	    AMap.event.addListener(autocomplete, "select", function(e){
	        placeSearch.search(e.poi.name);
	    });
	});
	AMap.event.addListener(chargingStationMap, 'click', getLnglat);
	addMarker(position, "static/images/chargingStationMap.png");
}
function getLnglat(e){
	if(deleteFlag != "details"){
		selectPosition = [];
		selectPosition.push(e && e.lnglat && e.lnglat.getLng() || 0);
		selectPosition.push(e && e.lnglat && e.lnglat.getLat() || 0);
		addMarker(selectPosition, "static/images/chargingStationMap.png");
	}
}
function addMarker(position, icon){
	if (position && position.length > 0) {
		chargingStationMap.remove(markers);
		markers = [];
		marker = new AMap.Marker({
			icon: icon,
	        map: chargingStationMap,
	        position: position,
	        animation: "AMAP_ANIMATION_DROP"
	    });
		markers.push(marker);
		marker = null;
	}
}
function changeImage(index) {
	$("#imageForm").empty();
	$("#imageForm").append('<input id="chargingStationImage" name="chargingStationImage" type="file" multiple class="file-loading"/>');
	if (index != undefined) {
		var imageUrl = "getChargingStationImage";
		var imageNameList = chargingStationData && chargingStationData[index] && chargingStationData[index].chargingStationImageName || [];
		var length = imageNameList.length;
		chargingStationData[index].initialPreview = [];
		chargingStationData[index].initialPreviewConfig = [];
		for (var i=0; i<length; i++) {
			chargingStationData[index].initialPreview.push('<img src="' + imageUrl + '?subfolder=' + chargingStationData[index].chargingStationID + '&&fileName=' + imageNameList[i] + '" style="width:220px;height:110px;" />');
			chargingStationData[index].initialPreviewConfig.push({url: "deleteChargingStationImage", extra: {fileName: imageNameList[i], subfolder: chargingStationData[index].chargingStationID}});
		}
	}
	var showBrowse = true;
	var showUpload = true;
		showUpload = false;
	var maxFileCount = 5 - (chargingStationData && chargingStationData[index] && chargingStationData[index].chargingStationImageName && chargingStationData[index].chargingStationImageName.length || 0)
	var option = {
		uploadUrl: "saveChargingStationImage",
		allowedFileExtensions: ['jpg', 'png','gif'], 
		showUpload: showUpload, 
		showCaption: false, 
		showClose: false, 
		overwriteInitial: false, 
		showKvUpload: false, 
		showErrorPreview: false, 
		uploadExtraData: {subfolder: chargingStationData && chargingStationData[index] && chargingStationData[index].chargingStationID}, 
		maxFileCount: maxFileCount,
		enctype: 'multipart/form-data',
		initialPreview: chargingStationData && chargingStationData[index] && chargingStationData[index].initialPreview,
		previewSettings: {image: {width: "220px", height: "100px"}},
		initialPreviewConfig: chargingStationData && chargingStationData[index] && chargingStationData[index].initialPreviewConfig,
		showBrowse: showBrowse,
		index: index
	};
	selectFile("chargingStationImage", option, resetPreview);
}
function resetPreview(data) {
	if (data) {
		var index = data.index;
		var imageNameList = chargingStationData && chargingStationData[index] && chargingStationData[index].chargingStationImageName || [];
		var file = data.file;
		if (data.flag == "delete" && file) {
			var imgIndex = imageNameList.indexOf(file);
			chargingStationData[index].chargingStationImageName.splice(imgIndex, 1);
			changeImage(index);
		} else if (data.flag == "uploaded" && file) {
			var length = file.length;
			for (var i=0; i<length; i++) {
				chargingStationData[index].chargingStationImageName.push(file[i].name);
			}
			changeImage(index);
		}
	}
}